<?php
/**
 * Auth.php
 *
 * 跨境电商商城系统
 * =========================================================
 * Copy right 2016-2026 大连熠泽科技网络有限公司
 * ----------------------------------------------
 * 官方网址: http://www.yizehuitong.com

 * 任何企业和个人不允许对程序代码以任何形式任何目的再发布。
 * =========================================================
 * @author : yizeteam
 * @date : 2019.10
 * @version : v2.0
 */

namespace data\service;

//所有model
use data\model\NsAppletModel;
use data\model\NsAppletCategoryModel;
use data\model\NsGoodsCategoryModel;
use data\model\NsGoodsSkuModel;
use data\model\NsGoodsModel;

//所有service
use data\service\User as User;

//tp框架类
use think\Cache;
use think\Db;

class Applet extends User
{
    /**
     * 添加小程序
     */
    public function addApplet($data)
    {
        $applet_model = new NsAppletModel();
        $res = $applet_model->save($data);
        if($res){
            return AjaxReturn(SUCCESS, ['applet_id' => $res], '添加成功');
        }else{
            return AjaxReturn(ERROR, [], '添加失败');
        }
    }

    /**
     * 修改小程序
     */
    public function editApplet($data, $condition)
    {
        $applet_model = new NsAppletModel();
        $res = $applet_model->save($data, $condition);
        if($res != false){
            return AjaxReturn(SUCCESS, ['applet_id' => $res], '修改成功');
        }else{
            return AjaxReturn(ERROR, [], '修改失败');
        }
    }

    /**
     * 获取小程序列表
     */
    public function getAppletPageList($page_index = 1, $page_size = 0, $condition = [], $order = '', $field = '*')
    {
        $applet_model = new NsAppletModel();
        $res = $applet_model->pageQuery($page_index, $page_size, $condition, $order, $field);
        return $res;
    }

    /**
     * 获取小程序信息
     */
    public function getAppletInfo($condition, $field = '*')
    {
        $applet_model = new NsAppletModel();
        $info = $applet_model->getInfo($condition, $field);
        return $info;
    }

    /**
     * 删除小程序
     */
    public function deleteApplet($applet_id)
    {
        $applet_model = new NsAppletModel();
        $res = $applet_model->destroy(['applet_id' => $applet_id]);
        if($res){
            return AjaxReturn(SUCCESS, [], '删除成功');
        }else{
            return AjaxReturn(ERROR, [], '删除失败');
        }
    }

    /**
     * 设置小程序关联商品分类
     */
    public function setAppletCategory($category_ids, $applet_id = 0)
    {
        Db::startTrans();
        try{
            $applet_category_model  = new NsAppletCategoryModel();
            $category_model         = new NsGoodsCategoryModel();

            $applet_category_model->destroy(['category_id' => ['in', $category_ids]]);
            $category_model->save(['applet_id' => $applet_id], ['category_id' => ['in', $category_ids]]);

            if($applet_id != 0){
                $category_id_arr = explode(',', $category_ids);
                $data = [];
                foreach($category_id_arr as $category_id){
                    $data[] = [
                        'applet_id' => $applet_id,
                        'category_id' => $category_id,
                    ];
                }
                $applet_category_model->saveAll($data);
            }

            Db::commit();
            return AjaxReturn(SUCCESS, [], '设置成功');
        }catch(\Exception $e){
            Db::rollback();
            return AjaxReturn(ERROR, [], $e->getMessage());
        }
    }


    /**
     * 通过条件获取分类id数据
     * @param $param
     * @return array
     */
    public function getCategoryIdsByCondition($param)
    {
        $is_applet = $param['is_applet'];
        $appid = $param['appid'];

        //根据是否是小程序和小程序appid获取对应的商品分类数据
        $condition = [];
        if($is_applet == 1){
            $applet_category_model = new NsAppletCategoryModel();
            $condition[] = ['exp', "applet_id in (select applet_id from ns_applet where appid = '{$appid}')"];
            $list = $applet_category_model->getQuery($condition, 'category_id', 'category_id asc');
        }else{
            //不是小程序用排除法
            $condition['pid'] = 0;
            $condition[] = ['exp', "category_id not in (select category_id from ns_applet_category)"];
            $category_model = new NsGoodsCategoryModel();
            $list = $category_model->getQuery($condition, 'category_id', 'category_id asc');
        }
        if(empty($list)) $list = [];

        $id_arr = [];
        foreach($list as $val){
            $id_arr[] = $val['category_id'];
        }

        return join(',', $id_arr);
    }

    /**
     * 通过sku_list 查询订单商品归属的小程序
     * @param $goods_sku_list
     * @return array 返回0个或多个applet_id的数组
     */
    public function getAppletIdByGoodsSkuList($goods_sku_list)
    {
        $goods_sku_model = new NsGoodsSkuModel();

        //goods_sku_list格式 sku_id:sku_num,sku_id:sku_num 通过正则去掉冒号和sku_num
        $sku_ids = preg_replace("/:\d+/", '', $goods_sku_list);

        //查询数据
        $list = $goods_sku_model
            ->alias('sku')
            ->join([
                ['ns_goods g', 'sku.goods_id = g.goods_id', 'left'],
                ['ns_goods_category c', 'g.category_id_1 = c.category_id', 'left'],
                ['ns_applet_category ac', 'c.category_id = ac.category_id', 'left']
            ])
            ->field('ac.applet_id')
            ->where(['sku.sku_id' => ['in', $sku_ids]])
            ->select();

        //组装applet_id数组
        $applet_id_arr = [];
        foreach($list as $val){
            if(!empty($val['applet_id'])){
                $applet_id = $val['applet_id'];
                if(!in_array($applet_id, $applet_id_arr)){
                    $applet_id_arr[] = $applet_id;
                }
            }
        }

        //根据获取的applet_id数量返回结果
        $applet_count = count($applet_id_arr);
        if($applet_count == 0){
            $res = success(['applet_id' => 0]);
        }else if($applet_count == 1){
            $res = success(['applet_id' => $applet_id_arr[0]]);
        }else{
            $res = error([], GOODS_BELONG_DIFFERENT_APPLET);
        }
        return $res;
    }

    /**
     * 获取所有端口
     * @return array
     */
    public function getPorts()
    {
        $data = array(
            array(
                'id'    => 0,
                'name'  => 'wap&pc'
            )
        );
        $applet_model = new NsAppletModel();
        $applet_data = $applet_model->getQuery([], 'applet_id, applet_name');
        if (!empty($applet_data)) {
            foreach ($applet_data as $val) {
                $data[] = array(
                    'id'    => $val['applet_id'],
                    'name'  => $val['applet_name']
                );
            }
        }
        return $data;
    }

    /**
     * 检测商品的端口是否相同
     * @param string $goods_ids     商品ID字符串
     * @return int                  返回值 1 : 相同, 0 : 不相同
     */
    public function checkGoodsPortIsSame($goods_ids)
    {
        $goods_model            = new NsGoodsModel();
        $applet_category_model  = new NsAppletCategoryModel();

        $result     = 1;
        $port_data  = [];

        if (empty($goods_ids)) return $result;
        $goods_id_arr   = explode(',', $goods_ids);

        foreach ($goods_id_arr as $goods_id) {
            $goods_info = $goods_model->getInfo(['goods_id' => $goods_id], 'category_id_1');

            if (empty($goods_info)) {
                $port_data[] = 0;
            } else {
                $applet_category_info = $applet_category_model->getInfo(['category_id' => $goods_info['category_id_1']], 'applet_id');
                if (empty($applet_category_info)) {
                    $port_data[] = 0;
                } else {
                    $port_data[] = $applet_category_info['applet_id'];
                }
            }
            $port_data = array_unique($port_data);
            if (count($port_data) >= 2) {
                $result = 0;
                break;
            }
        }
        return $result;
    }

    /**
     * 检测商品是否属于当前端口
     * @param string $goods_ids         商品ID字符串
     * @param string $category_ids_1    当前端口关联的所有一级商品分类ID字符串
     * @return int                      返回值 1 : 是, 0 : 否
     */
    public function checkGoodsIsBelongCurrPort($goods_ids, $category_ids_1)
    {
        $goods_model = new NsGoodsModel();

        $result = 1;

        if (empty($goods_ids)) return 0;
        $goods_id_arr = explode(',', $goods_ids);

        foreach ($goods_id_arr as $goods_id) {
            $goods_info = $goods_model->getInfo(['goods_id' => $goods_id], 'category_id_1');

            if (empty($goods_info)) {
                $result = 0;
                break;
            } else {
                if (!in_array($goods_info['category_id_1'], explode(',', $category_ids_1))) {
                    $result = 0;
                    break;
                }
            }
        }
        return $result;
    }


    /**
     * 通过商品分类ID,获取关联的小程序
     * @param $category_id
     * @return array|false|mixed|null|\PDOStatement|string|\think\Model
     */
    public function getAppletInfoByCategoryId($category_id)
    {
        $category_model = new NsGoodsCategoryModel();

        $result = [];
        $category_info = $category_model->getInfo(['category_id' => $category_id], 'applet_id');
        if (!empty($category_info) && $category_info['applet_id'] > 0) {
            $applet_model = new NsAppletModel();
            $applet_info = $applet_model->getInfo(['applet_id' => $category_info['applet_id']], 'applet_id, applet_name');
            !empty($applet_info) && $result = $applet_info;
        }
        return $result;
    }
}